package com.citydo.webrtcspringboot;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
@EnableScheduling
@ServletComponentScan
public class WebrtcspringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebrtcspringbootApplication.class, args);
        System.out.println("start success!");

        //命令行参数
        if(args.length>0)
            GlobalConfig.IP = args[0];

//        StudentServiceImpl studentService = new StudentServiceImpl();
//        List<Student> students = studentService.getAllStu发送消息:{time:1,speed:0}dent();
//        for(Student student : students){
//            System.out.println(student.toString());
//        }
    }


    public void udp(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(9876);

            byte[] buffer = new byte[1024];

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                String message = new String(packet.getData(), 0, packet.getLength());
                System.out.println("Received message from client: " + message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 替换json框架为fastjson
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2:添加fastJson的配置信息;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //指定当属性值为null是否输出：pro:null
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullListAsEmpty);
        //3处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //返回构成用的组件Bean
        return new HttpMessageConverters((HttpMessageConverter<?>) fastConverter);

    }

}
